import { login } from "@/api/epgms/account/login";
import { getUserInfo ,getUserInfo2} from "@/api/epgms/account/getUserInfo";
import { logout } from "@/api/epgms/account/logout";
import filterAsyncRoutes from "@/core/addRoutePermission";
import {
  setToken,
  getToken,
  setOfficerInfo,
  getOfficerInfo,
  setUserName,
  getUserName,
  removeToken,
  
} from "@/core/auth";

const state = {
  token: getToken(),
  userName: getUserName(),
  account: "",
  avatar: "",
  sidebar: true,
  routes: [],
  officerInfo: getOfficerInfo()// 新增状态
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, userName) => {
    state.userName = userName;
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_SIDEBAR: (state) => {
    state.sidebar = !state.sidebar;
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes;
  },
  SET_OFFICER_INFO: (state, officerInfo) => {
    state.officerInfo = officerInfo; // 新增mutation
    
  },
};
const actions = {
  
  async LoginAction(context, userInfo) {
    const { account, password } = userInfo;
    return login({
      account: account.trim(),
      password: password.trim(),
    }).then(result => {
      // 兼容多种后端返回格式：{ state, message, data } 或 { code, message, data } 或 直接返回 data
      if (result == null) {
        return Promise.reject(new Error('登录失败：无响应'));
      }

      let success = false;
      let data = null;
      let message = '';

      if (typeof result.state !== 'undefined') {
        success = result.state === 0;
        data = result.data;
        message = result.message;
      } else if (typeof result.code !== 'undefined') {
        // 一些后端使用 code 字段（例如 code===2000 表示成功）
        success = result.code === 2000 || result.code === 0;
        data = result.data || result;
        message = result.message;
      } else {
        // 直接返回业务数据
        success = true;
        data = result;
      }

      if (!success) {
        return Promise.reject(new Error(message || '登录失败'));
      }

      if (!data) {
        return Promise.reject(new Error('登录失败：无效的响应数据'));
      }

      // 从响应数据中获取所需信息
      const { token, name: userName, avatar, account: userAccount } = data;
      context.commit("SET_TOKEN", token);
      context.commit("SET_NAME", userName);
      context.commit("SET_AVATAR", avatar);
      context.commit("SET_ACCOUNT", userAccount);
      context.commit("SET_OFFICER_INFO", data); // 存储警员信息
      setToken(token);
      setUserName(data.name);
      setOfficerInfo(data);

      return result;
    });
  },

  // 获取用户信息
  async GetUserInfo(context, token) {
    // if (state.officerInfo==null) {
    //   token = getToken();
    //   const result = await getUserInfo(token);
    //   const { data } = result;
    //   const { roles } = data;
    //   return roles; 
    // }

    if (state.officerInfo.officerAccount.role==1) {
      token = getToken();
    const result = await getUserInfo2(token);
    const { data } = result;
    const { roles } = data;
    return roles; 
    }else {
      console.log("-----------------------------------------")
      token = getToken();
      const result = await getUserInfo(token);
      const { data } = result;
      const { roles } = data;
      return roles;
    }

    // token = getToken();
    // const result = await getUserInfo(token);
    // const { data } = result;
    // const { roles } = data;
    // return roles;
  },

  // 退出登录
  async Logout(context) {
    logout(state.officerInfo.officerAccount).then(() => {
      context.commit("SET_TOKEN", "");
      context.commit("SET_NAME", "");
      context.commit("SET_AVATAR", "");
      context.commit("SET_ACCOUNT", "");
      removeToken();
      window.location.reload()
    });
  },

  // sidebar status
  ChangeSidebar(context) {
    context.commit("SET_SIDEBAR");
  },

  async GenerateRoutes(context, roles) {
    const accessedRoutes = await filterAsyncRoutes(roles);
    context.commit("SET_ROUTES", accessedRoutes);
    return accessedRoutes;
  },
};

export default {
  namespaced: false, // 改为 false，这样可以直接访问 action
  state,
  mutations,
  actions,
};


// store/index.js


